// loginRoute.js
const express = require('express');
const executeQuery = require('../MySQL/connect');
const { setToken } = require('../token/token');
const router = express.Router();

router.post('/', async (req, res) => {
  const ip = req.ip;
  const codeMap = global.codeMap;
  const limitTime = global.limitTime;

  if (!codeMap[ip] || (+new Date()) - codeMap[ip].time > limitTime || codeMap[ip]?.value !== req.body.captcha) {
    return res.status(404).send('验证码无效或过期');
  }

  const sql = 'SELECT * FROM admin WHERE name = ? AND pass = ?';
  const values = [req.body.name, req.body.pass];

  try {
    // 使用 await 来等待查询结果
    const result = await executeQuery(sql, values);

    if (result.length > 0) {
      // 验证通过，生成并返回 Token
      const token = setToken(req.body.name, req.body.pass);
      console.log(global.codeMap);
      return res.status(200).send({ Token: token, msg: '登录成功' });
    } else {
      return res.status(404).send('登录失败，请检查用户名密码');
    }
  } catch (error) {
    console.error('Error: ' + error);
    return res.status(500).send('服务器错误');
  }
});

module.exports = router;
